package com.gaxy.wechat.handler;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信消息工厂，统一管理接口
 *
 * @author Gaxy
 * @create 2024/06/14/上午 11:03
 */
@Component
//InitializingBean是Spring框架提供的一个接口
//当一个类实现这个接口时，表明该类需要在所有必需属性设置后执行一些初始化工作
//接口中定义了一个方法:afterPropertiesSet()
//当一个Bean实例化并注入所有依赖项后，Spring容器会自动调用afterPropertiesSet方法
public class WeChatMsgFactory implements InitializingBean {
    @Resource
    private List<WeChatMsgHandler> wechatMsgHandlerList;

    private Map<WeChatMsgTypeEnum, WeChatMsgHandler> handlerMap = new HashMap<>();

    public WeChatMsgHandler getHandlerByMsgType(String msgType) {
        WeChatMsgTypeEnum msgTypeEnum = WeChatMsgTypeEnum.getByMsgType(msgType);
        return handlerMap.get(msgTypeEnum);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        for (WeChatMsgHandler wechatMsgHandler : wechatMsgHandlerList) {
            handlerMap.put(wechatMsgHandler.getMsgType(), wechatMsgHandler);
        }
    }



}
